package com.bsoft.gol.hcs.specialist.dao;


import com.bsoft.gol.hcs.clinical.bean.vo.TreatmentCodeVo;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import ctd.util.converter.ConversionUtils;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.transform.Transformers;
import com.bsoft.gol.hcs.specialist.bean.request.GroupChronicRecordQo;
import com.bsoft.gol.hcs.specialist.bean.response.PatientSearchProcess;
import com.bsoft.gol.hcs.specialist.bean.response.TreatmentRecordResponse;
import com.bsoft.gol.hcs.specialist.bean.response.TreatmentTimeInfoResponse;
import com.bsoft.gol.hcs.specialist.entity.PatientSearchRuleDetail;
import com.bsoft.gol.hcs.specialist.entity.TreatmentRecordEntity;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.DateUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 治疗记录dao层
 *
 * @author lanyu
 * @date 2021年10月14日 11:04
 */
public abstract class TreatmentRecordDAO extends HibernateSupportDelegateDAO<TreatmentRecordEntity> {

    @DAOMethod(sql = "from TreatmentRecordEntity where businessType=:businessType and visitId=:visitId")
    public abstract List<TreatmentRecordEntity> queryTreatmentRecordEntityList(@DAOParam("businessType") String businessType,@DAOParam("visitId") String visitId);

    /**
     * 根据机构id和报告id获取治疗信息
     *
     * @param requestId
     * @param reportOrganization
     * @return
     */
    @DAOMethod(sql = "from TreatmentRecordEntity where requestId=:requestId and reportOrganization=:reportOrganization")
    public abstract TreatmentRecordEntity getTreatmentRecordByRequestId(@DAOParam("requestId") String requestId, @DAOParam("reportOrganization") String reportOrganization);

    /**
     * 查询同步数量
     * @param startTime
     * @param endTime
     * @return
     */
    @DAOMethod(sql = "select count(1) from TreatmentRecordEntity  where  reportDatetime>=:startTime and reportDatetime<=:endTime")
    public abstract Long getTreatmentInfoByToday(@DAOParam("startTime") Date startTime,@DAOParam("endTime") Date endTime);
    /**
     * 更新删除标识
     */
    @DAOMethod(sql = "update TreatmentRecordEntity set deleteFlag='1' where  businessId in(:businessIdList) ")
    public abstract void updateDeleteFlag(@DAOParam("businessIdList") List<String> businessIdList);

    /**
     * 根据日期删除记录
     * @param resultDate
     */
    @DAOMethod(sql = "delete from PrescriptionRecordEntity where prescription_date <:resultDate and deleteFlag!='1'")
    public abstract void deleteTreatmentOverdueData(@DAOParam("resultDate") Date resultDate);
    /**
     * 获取治疗信息
     *
     * @return
     */
    public List<TreatmentCodeVo> queryTreatmentCodeList() {
        HibernateStatelessResultAction<List<TreatmentCodeVo>> action =
                new AbstractHibernateStatelessResultAction<List<TreatmentCodeVo>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("SELECT DISTINCT treatment_item_code as treatmentCode,treatment_item_name as treatmentName FROM treatment_record ");
                        Query query = ss.createSQLQuery(sqlBuilder.toString());
                        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                        List<Map> list = query.list();
                        List<TreatmentCodeVo> voList = new ArrayList<>();
                        if (CommonUtils.isNotEmpty(list)) {
                            for (Map map : list) {
                                voList.add(ConversionUtils.convert(map, TreatmentCodeVo.class));
                            }
                        } else {
                            voList = new ArrayList<>();
                        }
                        setResult(voList);
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     * 根据治疗项目获取患者信息
     *
     * @param patientSearchRuleDetail
     * @param recordStartTime
     * @param recordEndTime
     * @return
     */
    public List<PatientSearchProcess> queryPatientByTreatmentRecord(final PatientSearchRuleDetail patientSearchRuleDetail, final Date recordStartTime, final Date recordEndTime) {
        HibernateStatelessResultAction<List<PatientSearchProcess>> action =
                new AbstractHibernateStatelessResultAction<List<PatientSearchProcess>>() {
                    @Override
                    public void execute(StatelessSession ss) throws Exception {
                        StringBuilder sqlBuilder = new StringBuilder();
                        sqlBuilder.append("SELECT " +
                                "t.source_patient_id as patientId, " +
                                "t.NAME AS patientName, " +
                                "t.report_organization as organizationId, " +
                                "t.report_organization_name as organizationName, " +
                                "t.sex AS patientSex, " +
                                "t.business_type AS source, " +
                                "t.id_card AS cardNumber, " +
                                "substring_index(t.age,'岁',1) as patientAge, " +
                                "CASE " +
                                "WHEN t.business_type = 1 THEN " +
                                "t.clinic_id ELSE t.hospization_id " +
                                "END AS patientNumber," +
                                "( SELECT GROUP_CONCAT( distinct f.chronic_disease_id ) FROM fus_team_chronic_group_record f WHERE t.id_card = f.card_number and f.apply_status = '1') AS chronicDiseaseIds,"+
                                "( SELECT GROUP_CONCAT( distinct f.chronic_disease_name ) FROM fus_team_chronic_group_record f WHERE t.id_card = f.card_number and f.apply_status = '1') AS chronicDiseaseName " +
                                "FROM " +
                                "treatment_record t where  ");
                        sqlBuilder.append(" t.treatment_item_name =:firstConditionName ");
                        if (CommonUtils.isNotEmpty(recordStartTime) && CommonUtils.isNotEmpty(recordEndTime)) {
                            sqlBuilder.append(" and t.request_datetime >=:recordStartTime and t.request_datetime <=:recordEndTime ");
                        }
                        Query query = ss.createSQLQuery(sqlBuilder.toString());
                        query.setParameter("firstConditionName", patientSearchRuleDetail.getFirstConditionName());
                        if (CommonUtils.isNotEmpty(recordStartTime) && CommonUtils.isNotEmpty(recordEndTime)) {
                            query.setParameter("recordStartTime", DateUtil.dateFormate(recordStartTime,"yyyy-MM-dd"));
                            query.setParameter("recordEndTime", DateUtil.dateFormate(recordEndTime,"yyyy-MM-dd"));
                        }
                        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
                        List<Map> list = query.list();
                        List<PatientSearchProcess> voList = new ArrayList<>();
                        if (CommonUtils.isNotEmpty(list)) {
                            for (Map map : list) {
                                voList.add(ConversionUtils.convert(map, PatientSearchProcess.class));
                            }
                        } else {
                            voList = new ArrayList<>();
                        }
                        setResult(voList);
                    }
                };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }

    /**
     *
     * 根据病人idCard获取治疗信息
     * @param qo
     * @return
     */
    public List<TreatmentRecordResponse> queryTreatmentInfoByIdCard(GroupChronicRecordQo qo) {
        HibernateStatelessResultAction<List<TreatmentRecordResponse>> action = new AbstractHibernateStatelessResultAction<List<TreatmentRecordResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT treatment_item_code as treatmentCode,treatment_item_name as treatmentName FROM treatment_record WHERE id_card =:idCard ");
                sqlBuilder.append(" and request_datetime >=:beginTime and request_datetime <=:endTime group by treatment_item_code,treatment_item_name ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("idCard", qo.getIdCard());
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<TreatmentRecordResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, TreatmentRecordResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
    /**
     * 获取治疗时间信息
     * @param qo
     * @param treatmentCode
     * @return
     */
    public List<TreatmentTimeInfoResponse> queryTreatmentTimeListByIdCard(GroupChronicRecordQo qo, String treatmentCode) {
        HibernateStatelessResultAction<List<TreatmentTimeInfoResponse>> action = new AbstractHibernateStatelessResultAction<List<TreatmentTimeInfoResponse>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuilder sqlBuilder = new StringBuilder();
                sqlBuilder.append("SELECT treatment_item_code as treatmentCode,treatment_item_name as treatmentName,request_datetime as treatmentTime FROM treatment_record WHERE id_card =:idCard and treatment_item_code =:treatmentCode ");
                sqlBuilder.append(" and request_datetime >=:beginTime and request_datetime <=:endTime order by request_datetime ");
                Query query = ss.createSQLQuery(sqlBuilder.toString());
                query.setParameter("idCard", qo.getIdCard());
                query.setParameter("treatmentCode", treatmentCode);
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("beginTime", qo.getBeginTime()+" 00:00:00");
                }
                if (CommonUtils.isNotEmpty(qo.getBeginTime())){
                    query.setParameter("endTime", qo.getEndTime()+" 23:59:59");
                }
                query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);
                List<Map> list = query.list();
                List<TreatmentTimeInfoResponse> voList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(list)) {
                    for (Map map : list) {
                        voList.add(ConversionUtils.convert(map, TreatmentTimeInfoResponse.class));
                    }
                } else {
                    voList = new ArrayList<>();
                }
                setResult(voList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        return action.getResult();
    }
}
